//
//  MainTableViewController.m
//  3 - 25 天气预报作业
//
//  Created by student on 16/3/26.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "MainTableViewController.h"
#import "Model.h"
@interface MainTableViewController ()<NSXMLParserDelegate,UITableViewDataSource,UITableViewDelegate>

@property (strong,nonatomic) NSMutableArray *mArr;
@end

@implementation MainTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"全国天气";
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://flash.weather.com.cn/wmaps/xml/%@.xml",self.pyName]]];
    //创建一个解析器
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    //代理人
    parser.delegate = self;
    
    //开始解析
    [parser parse];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.mArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }
    Model *m = self.mArr[indexPath.row];
    if (m.quName)
    {
        cell.textLabel.text = m.quName;
    }
    else
    {
        cell.textLabel.text = m.cityname;
    }
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@",m.stateDetailed,m.windState];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainTableViewController *city = [[MainTableViewController alloc] init];
    Model *m = self.mArr[indexPath.row];
    city.pyName = m.pyName;
    if (m.pyName != nil)
    {
        [self.navigationController pushViewController:city animated:YES];
    }
}

#pragma mark - 方法

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    self.mArr = [NSMutableArray array];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict
{
    if ([elementName isEqualToString:@"city"])
    {
        Model *m = [Model modeWithDict:attributeDict];
        [self.mArr addObject:m];
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    [self.tableView reloadData];
}




@end
